/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.trandio.manager;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.trandio.dao.AdmisionDAO;
import org.trandio.dao.AdmisionInterface;
import org.trandio.model.AdmisionVO;
import org.trandio.model.DetalleAdmisionVO;

/**
 *
 * @author root
 */
public class AdmisionServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            int idAdmision = 0;
            int idDetAdm = 0;

            AdmisionInterface admisionInterface = new AdmisionDAO();
            AdmisionVO admisionVO = new AdmisionVO();
            List<DetalleAdmisionVO> lisDetalleAdmisionVO = new ArrayList<DetalleAdmisionVO>();


            int op = Integer.parseInt(request.getParameter("op"));

            switch (op) {

                case 1: {
                    try {
                        admisionVO = admisionInterface.buscarEstadoAdmisionPaciente(request.getParameter("idpaciente"), request.getParameter("estado"));
                    } catch (SQLException ex) {
                        Logger.getLogger(AdmisionServlet.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (NamingException ex) {
                        Logger.getLogger(AdmisionServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    Gson gson = new Gson();
                    out.println(gson.toJson(admisionVO));
                }
                break;

                case 2: {
                    int viaIngId = 0;
                    int medId = 0;
                    int cauExtId = 0;
                    int diagId = 0;


                    Date fecha = new Date();
                    SimpleDateFormat formatoDeFecha = new SimpleDateFormat("dd/MM/yyyy HH:mm");
                    String fecFac = formatoDeFecha.format(fecha);


                    if (!request.getParameter("fecha_ingreso").equals("")) {
                        fecFac = request.getParameter("fecha_ingreso");
                    }


                    if (!request.getParameter("id_via_ingreso").equals("")) {
                        viaIngId = Integer.parseInt(request.getParameter("id_via_ingreso").trim());
                    }

                    if (!request.getParameter("id_medico").equals("")) {
                        medId = Integer.parseInt(request.getParameter("id_medico").trim());
                    }

                    if (!request.getParameter("id_causa_externa").equals("")) {
                        cauExtId = Integer.parseInt(request.getParameter("id_causa_externa").trim());
                    }


                    if (!request.getParameter("id_diagnostico").equals("")) {
                        diagId = Integer.parseInt(request.getParameter("id_diagnostico").trim());
                    }

                    try {
                        idAdmision = admisionInterface.guardarAdmision(
                                request.getParameter("id_paciente"),
                                request.getParameter("id_estado"),
                                request.getParameter("id_usuario"),
                                request.getParameter("id_tipo_admision"),
                                request.getParameter("id_entidad"),
                                request.getParameter("id_contrato"),
                                String.valueOf(viaIngId),
                                request.getParameter("numero_autorizacion"),
                                String.valueOf(medId),
                                String.valueOf(cauExtId),
                                String.valueOf(diagId),
                                fecFac);

                    } catch (SQLException ex) {
                        Logger.getLogger(AdmisionServlet.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (NamingException ex) {
                        Logger.getLogger(AdmisionServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    out.println(idAdmision);
                    // out.println("{\"idadmision\":\"" + idAdmision + "\"}");
                    //out.println("{\"idadmision\":\""+idAdmision + "\"}");
                    //Gson gson = new Gson();
                    //out.println(gson.toJson(idAdmision));
                    //out.println(request.getParameter("op") + "=>" + idcontrato + "=>");
                }
                break;

                case 3: {

                    try {

                        idDetAdm = admisionInterface.guardarDetalleAdmision(
                                request.getParameter("idadmision"),
                                request.getParameter("idactividad").trim(),
                                request.getParameter("valorunitario"),
                                request.getParameter("valorsubsidio"),
                                request.getParameter("valorcopago"),
                                request.getParameter("cantidad"),
                                request.getParameter("valortotal"),
                                request.getParameter("idmedico"));

                    } catch (SQLException ex) {
                        Logger.getLogger(AdmisionServlet.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (NamingException ex) {
                        Logger.getLogger(AdmisionServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    out.println(idDetAdm);
                    // out.println("{\"iddetadm\":\"" + idDetAdm + "\"}");
                    //Gson gson = new Gson();
                    //out.println(gson.toJson(idDetAdm));
                }
                break;

                case 4: {

                    try {

                        try {

                            lisDetalleAdmisionVO = admisionInterface.buscarActividadesCargadasAdmisionId(Integer.parseInt(request.getParameter("idadmision")));

                            if (lisDetalleAdmisionVO.size() > 0) {

                                Iterator it = lisDetalleAdmisionVO.iterator();

                                out.println("<table id='tbl_actividades_cargadas_admision' align='center' class='ui-widget-content' width='100%'>");
                                out.println("<tr class='ui-state-default'>");
                                out.println("<th>&nbsp;</th><th width='50px'>C&oacute;digo</th><th width='600px'>Descripci&oacute;n</th><th width='25px' align='center'>Cant</th><th width='100px'>V. Total</th><th width='100px'>V. Entidad</th><th width='100px'>V. Paciente</th><th>RIP</th><th>Eliminar</th><th style='display:none'>&nbsp;</th><th style='display:none'>&nbsp;</th><th style='display:none'>&nbsp;</th><th style='display:none'>&nbsp;</th>");
                                out.println("</tr>");

                                while (it.hasNext()) {

                                    DetalleAdmisionVO da = (DetalleAdmisionVO) it.next();

                                    out.println("<tr class='ui-state-default'>");

                                    //id detalle admision
                                    out.println("<td>");

                                    out.println("<input type='checkbox' id='" + "aa" + da.getId() + "' />");
                                    out.println("</td>");

                                    //codigo act
                                    out.println("<td>");
                                    out.println(da.getCodigo());
                                    out.println("</td>");

                                    //descripcion act
                                    out.println("<td>");
                                    out.println(da.getDescripcion());
                                    out.println("</td>");

                                    //cantidad act
                                    out.println("<td align='center'>");
                                    out.println(da.getCantidad());
                                    out.println("</td>");

                                    //vr total act
                                    out.println("<td align='right'>");
                                    out.println(da.getVrunitario());
                                    out.println("</td>");

                                    //vr vrempresa/valor_subsidio
                                    out.println("<td align='right'>");
                                    out.println(da.getVraseguradora());
                                    out.println("</td>");

                                    //vr vrpaciente/copago
                                    out.println("<td align='right'>");
                                    out.println(da.getVrpaciente());
                                    out.println("</td>");

                                    out.println("<td align='center'>");
                                    out.println("<img onclick='eliminarDetalle(this.parentNode.parentNode)' style='cursor:pointer' src='../common/img/eliminar.png' alt='Eliminar' title='Eliminar'/>");
                                    out.println("</td>");

                                    out.println("<td align='center'>");
                                    out.println("<img onclick='eliminarDetalle(this.parentNode.parentNode)' style='cursor:pointer' src='../common/img/eliminar.png' alt='Eliminar' title='Eliminar'/>");
                                    out.println("</td>");

                                    out.println("<td style='display:none;'>");
                                    out.println(da.getIdactividad());
                                    out.println("</td>");

                                    out.println("<td style='display:none;'>");
                                    out.println(da.getId_admision());
                                    out.println("</td>");

                                    out.println("<td style='display:none;'>");
                                    out.println(da.getId_medico());
                                    out.println("</td>");

                                    out.println("<td style='display:none;'>");
                                    out.println(da.getTipoRegistro());
                                    out.println("</td>");

                                    out.println("<td style='display:none;'>");
                                    out.println(da.getId());
                                    out.println("</td>");

                                    //out.println("<td style='display:none;'>");                                    
                                    //out.println(da.getIdactividad() + "|" + da.getCodigo() + "|" + da.getDescripcion() + "|"+da.getCantidad()+ "|1|" + da.getVrunitario() + "|" + da.getId_medico());
                                    //out.println("</td>");                             

                                    out.println("</tr>");

                                }
                                out.println("</table>");
                            } else {
                                //out.println("carlos");
                            }

                        } catch (SQLException ex) {
                            Logger.getLogger(AdmisionServlet.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (NamingException ex) {
                            Logger.getLogger(AdmisionServlet.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    } finally {
                        out.close();
                    }
                }
                break;

                case 5: {
                    try {
                        int idac, idad = 0;
                        idac = Integer.parseInt(request.getParameter("idactividad"));
                        idad = Integer.parseInt(request.getParameter("idadmision"));
                        admisionInterface.eliminarDetalleAdmision(idad,idac);
                    } catch (SQLException ex) {
                        Logger.getLogger(AdmisionServlet.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (NamingException ex) {
                        Logger.getLogger(AdmisionServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
                break;

            }
        } finally {
            out.close();
        }
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
